package org.luxor.common.netty.config;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import org.luxor.common.netty.config.option.SslOption;
import org.luxor.common.netty.config.properties.NettyClientProperties;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * 客户端通道流水线配置抽象类
 *
 * @author Mr.yan @date 2024/1/26
 */
public abstract class ClientPipelineConfig extends ChannelInitializer<Channel> {
    private final ResourceLoader resource = new DefaultResourceLoader();

    /**
     * 返回客户端配置
     *
     * @return org.luxor.common.netty.config.properties.NettyClientProperties
     */
    public abstract NettyClientProperties clientProperties();

    protected SslContext sslContext(SslOption sslOption) throws Exception {
        File certFile = resource.getResource(sslOption.getCertFile()).getFile();
        File keyFile = resource.getResource(sslOption.getKeyFile()).getFile();
        String keyPassword = sslOption.getKeyPassword();
        File caCertFile = null;
        if (StringUtils.hasText(sslOption.getCaCertFile())) {
            caCertFile = resource.getResource(sslOption.getCaCertFile()).getFile();
        }
        return SslContextBuilder.forClient()
                // 如果是单向认证，则可以注释该行
                .keyManager(certFile, keyFile, keyPassword)
                .trustManager(caCertFile)
                .sslProvider(SslProvider.OPENSSL)
                .build();
    }
}
